const models     = require('../models');
const Reply      = models.Reply;
const EventProxy = require('eventproxy');
const tools      = require('../common/tools');
const User       = require('./user');
const at         = require('../common/at');


/**
 * 根据主题ID，获取回复列表
 * Callback:
 * - err, 数据库异常
 * - replies, 回复列表
 * @param {String} id 主题ID
 * @param {Function} callback 回调函数
 */
exports.getRepliesByTopicId = function (id, callback) {
    Reply.find({topic_id: id, deleted: false}, '', {sort: 'create_at'}, function (err, replies) {
        if (err) {
            return callback(err);
        }
        if (replies.length === 0) {
            return callback(null, []);
        }

        // let ep = new EventProxy();
        // ep.after('reply_find', replies.length, function () {
        //     console.log('-----------------');
        //     callback(replies);
        // });

        for (var j = 0; j < replies.length; j++) {
            (function (i) {
                let author_id = replies[i]._doc.reply_id;

                // console.log('author_id=======', author_id);
                User.getUser({_id: author_id}, {}, function (err, author) {
                    if (err) {
                        return callback(err);
                    }
                    replies[i]._doc.author = author;

                    if(i >= replies.length -1) {
                        // ep.emit('reply_find');
                        return callback(replies);
                    }
                });
            })(j);
        }
    });
};

/**
 * 创建并保存一条回复信息
 * @param {String} content 回复内容
 * @param {String} topicId 主题ID
 * @param {String} authorId 回复作者
 * @param {String} [replyId] 回复ID，当二级回复时设定该值
 * @param {Function} callback 回调函数
 */
exports.newAndSave = function (content, topicId, authorId, replyId, callback) {
    if(typeof replyId === 'function') {
        callback = replyId;
        replyId = null;
    }

    let reply = new Reply();

    reply.content = content;
    reply.topic_id = topicId;
    reply.author_id = authorId;

    if (replyId) {
        reply.reply_id = replyId;
    }

    reply.save(function (err) {
        callback(err, reply);
    })
};

/**
 * 根据用户ID，获取回复列表
 * Callback:
 * - err, 数据库异常
 * - replies, 回复列表
 * @param {String} id 用户ID
 * @param {Function} callback 回调函数
 */
exports.getRepliesByUserId = function (id, opt, callback) {
    Reply.find({reply_id: id, deleted: false}, {}, opt, callback);
};

exports.getReplyById = function (id, callback) {
    Reply.findOne({_id: id}, callback);
};

/**
 * 根据topicId查询到最新的一条未删除回复
 * @param topicId 主题ID
 * @param callback 回调函数
 */
exports.getLastReplyByTopId = function (topicId, callback) {
    Reply.find({topic_id: topicId, deleted: false}, '_id', {sort: {create_at: -1}, limit: 1}, callback);
};